﻿using Core.FrameWork.Commons;
using Core.FrameWork.Commons.Http.Abstraction;
using Core.FrameWork.Models;
using Core.Polly.Web;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using System;
using System.Net;
using System.Net.Http;

namespace Core.Web.Api.Utils.Init
{
    public static class InitHttpClientFactory
    {
        public static void InitHttpClientPolly(this IServiceCollection services)
        {
            services.AddHttpClient(APIConfig.HttpClientPolly.HttpClientName)//配置服务名称
            .AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(APIConfig.HttpClientPolly.Timeout))) // 超时;
            .AddTransientHttpErrorPolicy(builder =>
                       {
                           //Polly重试机制
                           return builder.RetryAsync(APIConfig.HttpClientPolly.RetryNum, (res, index) =>
                           {
                               Console.WriteLine($"执行错误，异常行为：{res?.Result}");
                               Console.WriteLine($"第{index}次重试");
                           });
                       })
            .AddPolicyHandler(Policy<HttpResponseMessage>.Handle<Exception>().OrResult(s => s.StatusCode == HttpStatusCode.InternalServerError).CircuitBreakerAsync(APIConfig.HttpClientPolly.HandledEventsAllowedBeforeBreaking, TimeSpan.FromSeconds(APIConfig.HttpClientPolly.DurationOfBreak), (ex, ts) =>
                            {
                                Console.WriteLine($"断路器开启");
                                Console.WriteLine($"断路器开启时间：{ts.TotalSeconds}s");
                            }, () => { }
                            ));

            services.AddSingleton<IHttpClient, HttpClientFactory>();//添加Http调用封装类
        }
    }
}
